package com.edu.controller;

import com.edu.bean.User;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ModelController {

    @ModelAttribute
    public void init(){
        System.out.println("执行了init方法");
    }

    /**
     * @ModelAttribute 放在方法上，且方法返回值为void，在方法的参数中加入一个 Model对象
     *      向这个model中存入的数据，
     *      其他的方法的model中可以取出
     */
    @ModelAttribute
    public void init2(Model model){
        System.out.println("执行了 init2方法");
        model.addAttribute("msg","hello world");
        model.addAttribute("power","查询");
    }

    /**
     * 方法方法上，@ModelAttribute("note")
     *  方法的返回值 会存入到Model中 名字是 note
     */

    @ModelAttribute("note")
    public String init3(){
        System.out.println("执行了init3方法");
        return "hello note";
    }

    @ModelAttribute("u")
    public User init4(){
        System.out.println("执行了init4方法");
        User user = new User();
        user.setUserId(1);
        user.setUsername("shufen");
        user.setPassword("654321");
        System.out.println(user.hashCode());
        return user;
    }

    @RequestMapping("/model01")
    public String test01(Model model){
        System.out.println("执行了 test01方法");
        System.out.println(model.getAttribute("msg"));
        System.out.println(model.getAttribute("power"));
        System.out.println(model.getAttribute("note"));
        return "redirect:index.jsp";
    }


    @RequestMapping("/model02")
    public String test02(Model model){
        System.out.println("执行了 test02方法");
        System.out.println(model.getAttribute("msg"));
        System.out.println(model.getAttribute("power"));
        System.out.println(model.getAttribute("note"));
        return "redirect:index.jsp";
    }

    @RequestMapping("/modelTest")
    public String modelTest(@ModelAttribute("u") User user){
        System.out.println(user);
        System.out.println(user.hashCode());
        return "redirect:index.jsp";
    }
}
